import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@store/index'
import {constantRouterMap} from "@/config/router.config";

Vue.use(VueRouter)
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({y:0}),
  routes: constantRouterMap
});



router.beforeEach((to,from,next)=> {
  console.info('beforeEach',to,from,next);
  // console.info('routes', router.app.$store.state.getters.routes);
  if(constantRouterMap.length === 0){
      let permissions = [
        {
          name: 'user',
          title: '用户管理',
          componentName:'UserList',
          url: '/user',
          component: 'views/user/UserList',
        },
        {
          name: 'role',
          url: '/role',
          title: '角色管理',
          component:'views/user/RoleList',
          componentName:'RoleList',
        },
        {
          name: 'test',
          title: '测试',
          url: '/test',
          component:'views/test',
          componentName:'test'
        }
      ]

      store.dispatch('generate',permissions).then(()=>{
        const redirect = decodeURIComponent(from.query.redirect || to.path)
        if (to.path === redirect) {
          // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          next({ ...to, replace: true })
        } else {
          // 跳转到目的路由
          next({ path: redirect })
        }
      })
  }else {
    next()
  }
});

router.afterEach(() => {
  console.info('afterEach');
});

export default router;
